package com.andriod.waker;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import com.andriod.waker.ConnectionHostActivity.BroadcastReciever;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class BroadcastSender implements Runnable {

	private boolean run;
	private final static byte start_request = 0; 
	private DatagramPacket dp = null;
	private DatagramSocket ds = null;
	private InetAddress dest;
	private byte[] key;
	private int port;
	private BroadcastReciever br;
	private Handler m_handler;
	private Message msg;
	
	public BroadcastSender(InetAddress dest,int port,BroadcastReciever bt,Handler handler)
	{
		br = bt;
		run = true;
		this.dest = dest;
		this.port = port;
		key = new byte[1];
		key[0] = start_request;
		
		try {
			ds = new DatagramSocket();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			Log.d("SOCKET_EXCEPTION_sender", e.toString());
			br.Close_thread();
			return;
		}
		
		m_handler = handler;
		msg = new Message();
		
		Log.d("IP_ADDRESS", dest.getHostAddress());
		Log.d("PORT", port + "");
	}
	
	public void run() {
		// TODO Auto-generated method stub
		dp = new DatagramPacket(key,key.length,dest,port);
		
		while(run)
		{
			try {
				ds.send(dp);
				Log.d("Sending!", "Sending!");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				Log.d("IO_EXCEPTION_sender", e1.toString());
				msg.what = 1;
				m_handler.sendMessage(msg);
				br.Close_thread();
				return;
			}
			
			try {
				Thread.sleep(400);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				Log.d("INTERRUPTED_EXCEPTION_sender", e.toString());
				br.Close_thread();
				return;
			}
		}
	}
	
	public void Close_thread()
	{
		if(run == true)
		{
			ds.close();
			run = false;
		}
	}
	
	public int Get_port()
	{
		return ds.getLocalPort();
	}
}